import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import MarkdownRenderer from '../components/MarkdownRenderer';
import styles from './DocsPage.module.scss';

const DocsPage = () => {
  const [content, setContent] = useState('');
  const location = useLocation();

  useEffect(() => {
    // 根据当前路径确定要加载的文档
    const path = location.pathname;
    
    // 移除开头的斜杠
    const pathParts = path.split('/').filter(Boolean);
    
    // 构建文档路径
    let docPath;
    if (pathParts.length === 1) {
      // 根级文档
      docPath = `../docs/${pathParts[0]}.md`;
    } else {
      // 嵌套目录文档
      const lastPart = pathParts.pop();
      const directory = pathParts.join('/');
      docPath = `../docs/${directory}/${lastPart}.md`;
    }
    
    // 使用import.meta.glob加载Markdown文件
    const docs = import.meta.glob('../docs/**/*.md', { query: '?raw', import: 'default' });
    
    if (docs[docPath]) {
      docs[docPath]()
        .then((text) => {
          setContent(text as string);
        })
        .catch((error) => {
          console.error('加载文档失败:', error);
          setContent('# 文档不存在\n\n请求的文档未找到。');
        });
    } else {
      setContent('# 文档不存在\n\n请求的文档未找到。\n\n路径: ' + docPath);
    }
  }, [location.pathname]);

  return (
    <div className={styles.docsPage}>
      <MarkdownRenderer content={content} />
    </div>
  );
};

export default DocsPage;